package com.hnucm.cooklife.ui.activity;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.baseadapter.BGAOnRVItemLongClickListener;
import cn.bingoogolapple.baseadapter.BGARecyclerViewAdapter;
import cn.bingoogolapple.baseadapter.BGAViewHolderHelper;
import cn.bingoogolapple.photopicker.activity.BGAPPToolbarActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.imageloader.BGARVOnScrollListener;
import cn.bingoogolapple.photopicker.widget.BGAImageView;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import com.amrdeveloper.reactbutton.ReactButton;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.hnucm.cooklife.R;
import com.hnucm.cooklife.base.BaseFragment;
import com.hnucm.cooklife.base.utils.FbReactions;
import com.hnucm.cooklife.base.utils.LoginUtils;
import com.hnucm.cooklife.base.utils.Moment;
import com.hnucm.cooklife.bean.db.Foll;
import com.hnucm.cooklife.contract.foll.Contract;
import com.hnucm.cooklife.presenter.home.FollPresenter;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

/**
 * 你自己项目里「可以不继承 BGAPPToolbarActivity」，我在这里继承 BGAPPToolbarActivity 只是为了方便写 Demo
 * BGAOnRVItemClickListener和BGAOnRVItemLongClickListener这两个接口是为了测试事件传递是否正确，你自己的项目里可以不实现这两个接口
 */

/**
 * 被用作了follfragment
 */
public class MomentListActivity extends BaseFragment<Contract.IFollView, FollPresenter> implements EasyPermissions.PermissionCallbacks, BGANinePhotoLayout.Delegate, BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, Contract.IFollView {

    private Context mContext;

    private List<Foll> mFollList = new ArrayList<>();

    @BindView(R.id.rv_moment_list_moments)
    RecyclerView mRecyclerView;

    private static final int PRC_PHOTO_PREVIEW = 1;

    private static final int RC_ADD_MOMENT = 1;

//    private RecyclerView mMomentRv;
    private MomentAdapter mMomentAdapter;

    /**
     * 设置图片预览时是否具有保存图片功能「测试接口用的」
     */
//    private CheckBox mDownLoadableCb;

    private BGANinePhotoLayout mCurrentClickNpl;

    @Override
    public void onLoadFoll(List<Foll> follList) {
        System.out.println("hh0");
        mFollList.addAll(follList);
        mMomentAdapter.setData(mFollList);
        System.out.println(mFollList);
    }

    @Override
    public void onRefreshFoll(List<Foll> follList) {

    }

    //    @Override
//    protected void setListener() {
//        mMomentAdapter = new MomentAdapter(mMomentRv);
//        mMomentAdapter.setOnRVItemClickListener(this);
//        mMomentAdapter.setOnRVItemLongClickListener(this);
//
//        mMomentRv.addOnScrollListener(new BGARVOnScrollListener(getActivity()));
//    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_moment_list;
    }

//    @OnClick(R.id.test)
//    public void click(){
//        Intent intent = new Intent(mContext, SystemGalleryActivity.class);
//        startActivity(intent);
//    }

    @Override
    protected void init() {
        mContext = getActivity().getApplicationContext();
        mMomentAdapter = new MomentAdapter(mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(mMomentAdapter);
        mMomentAdapter.setOnRVItemClickListener(this);
        mMomentAdapter.setOnRVItemLongClickListener(this);

        mPresenter.loadFoll(LoginUtils.getLoginId());
    }
    @Override
    protected FollPresenter createPresenter() {
        return new FollPresenter();
    }

//    public void onClick(View v) {
//        if (v.getId() == R.id.tv_moment_list_add) {
//            startActivityForResult(new Intent(mContext, MomentAddActivity.class), RC_ADD_MOMENT);
//        } else if (v.getId() == R.id.tv_moment_list_system) {
//            startActivity(new Intent(mContext, SystemGalleryActivity.class));
//        }
//    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && requestCode == RC_ADD_MOMENT) {
//            mMomentAdapter.addFirstItem(MomentAddActivity.getMoment(data));
//            mRecyclerView.smoothScrollToPosition(0);
//        }
//    }

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            File downloadDir = new File(Environment.getExternalStorageDirectory(), "FollPicDown");
            BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(mContext);

//            if (mDownLoadableCb.isChecked()) {
                // 保存图片的目录，如果传 null，则没有保存图片功能
                photoPreviewIntentBuilder.saveImgDir(downloadDir);
//            }

            if (mCurrentClickNpl.getItemCount() == 1) {
                // 预览单张图片
                photoPreviewIntentBuilder.previewPhoto(mCurrentClickNpl.getCurrentClickItem());
            } else if (mCurrentClickNpl.getItemCount() > 1) {
                // 预览多张图片
                photoPreviewIntentBuilder.previewPhotos(mCurrentClickNpl.getData())
                        .currentPosition(mCurrentClickNpl.getCurrentClickItemPosition()); // 当前预览图片的索引
            }
            startActivity(photoPreviewIntentBuilder.build());
        } else {
            EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", PRC_PHOTO_PREVIEW, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PREVIEW) {
            Toast.makeText(mContext, "您拒绝了「图片预览」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        mCurrentClickNpl = ninePhotoLayout;
        photoPreviewWrapper();
    }

    @Override
    public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        ninePhotoLayout.setIsExpand(true);
        ninePhotoLayout.flushItems();
    }

    @Override
    public void onLoading() {
    }

    @Override
    public void onLoadingFailed() {

    }

    @Override
    public void onLoadSuccess() {

    }

    @Override
    public void onRVItemClick(ViewGroup viewGroup, View view, int position) {

        BGAImageView header = (BGAImageView) view.findViewById(R.id.foll_header);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int userId = mFollList.get(position).userId;
                Intent intent = new Intent(getActivity(),FriendActivity.class);

                intent.putExtra("userId",userId);
                startActivity(intent);
            }
        });

        ImageButton imageView = (ImageButton) view.findViewById(R.id.foll_menu);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIBottomSheet.BottomListSheetBuilder(getActivity())
                        .addItem(R.drawable.menu_me,"取消关注@" + mFollList.get(position).userName.toString(),"")
                        .addItem(R.drawable.menu_collect,"隐藏@" + mFollList.get(position).userName,"")
                        .setAddCancelBtn(true)
                        .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                            @Override
                            public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                                dialog.dismiss();
                                ToastUtils.showShort("hhsafi");
                            }
                        })
                        .build().show();
            }
        });
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup viewGroup, View view, int position) {
        Toast.makeText(mContext, "长按了item " + position, Toast.LENGTH_SHORT).show();
        return true;
    }

    private class MomentAdapter extends BGARecyclerViewAdapter<Foll> {
        private List<Foll> mFolls = new ArrayList<>();
        public MomentAdapter(RecyclerView recyclerView) {
            super(recyclerView, R.layout.item_moment);
        }

        @Override
        protected void fillData(BGAViewHolderHelper helper, int position, Foll foll) {
            if (TextUtils.isEmpty(foll.userContent)) {
                helper.setVisibility(R.id.foll_content, View.GONE);
            } else {
                helper.setVisibility(R.id.foll_content, View.VISIBLE);
                helper.setText(R.id.foll_content, foll.userContent);
            }

            Glide.with(mContext).load(foll.userHeader).into(helper.getImageView(R.id.foll_header));

            helper.setText(R.id.foll_name,foll.userName);

            BGANinePhotoLayout ninePhotoLayout = helper.getView(R.id.foll_pic);
            ninePhotoLayout.setDelegate(MomentListActivity.this);
            ninePhotoLayout.setData(foll.userPic);
        }
    }
}